package cn.fantasy.study;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 对象的创建方式
 * 1. 直接用构造方法创建
 * 2. 通过反射的形式来创建对象，起到解除耦合的效果
 * Class clazz = Class.forName("com.fantasy.study.service.Impl.UserServiceImpl");
 * UserService userservice = (UserService)clazz.newInstance();
 */
public class BeanFactory {

    private static Properties env = new Properties();

    static {
        // 第一步获得IO的输入流
        InputStream inputStream = BeanFactory.class.getResourceAsStream("/applicationContext.properties");
        // 文件的内容封装到Properties集合中，······
        try {
            env.load(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 对一下两个方法做了封装
     * @param key 传入的是配置文件中的key值
     * @return
     */
    public static Object getBean(String key) {
        Object ret = null;
        try {
            Class<?> clazz = Class.forName(env.getProperty(key));
            ret = clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return ret;
    }

//    public static IUserService getUserService() {
//        Class clazz = null;
//        IUserService iuserService = null;
//        try {
//            clazz = Class.forName(env.getProperty("userService"));
//            iuserService = (IUserService) clazz.newInstance();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        }
//        return iuserService;
//    }
//
//    public static IUserDao getUserDao() {
//        Class clazz = null;
//        IUserDao iuserdao = null;
//
//        try {
//            clazz = Class.forName(env.getProperty("userDao"));
//            iuserdao = (IUserDao) clazz.newInstance();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        }
//        return iuserdao;
//    }
}
